// ==UserScript==
// @name         steam简易版
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  自动出售当前物品，价格为当前市场价.
// @author       liQiang
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    addPanel();
})();
function addPanel(){
    function genDiv(cls, id){
        let d = document.createElement('div');
        d.style.cssText = 'vertical-align:middle;';
        if(cls){ d.className = cls };
        if(id){ d.id = id };
        return d;
    }
    //创建一个可以自由弹出的面板
    function genPanel(name, visiable){
        let panel = genDiv(name, name);
        panel.style.cssText = 'background: rgba(58, 58, 58, 0.8);position: fixed;top: 50%;right: 0px;';
        panel.style.cssText += 'text-align: center;transform: translate(0px, -50%);z-index: 100;';
        panel.style.cssText += 'border: 1px solid rgb(83, 83, 83);padding: 5px;border-radius: 10px 0 0 10px;';
        panel.style.cssText += 'transition:right 0.8s;right:-300px;'
        return panel;
    }
    function genButton(test, foo, id, fooParams = {}){
        let b = document.createElement('button');
        b.textContent = test;
        b.style.verticalAlign = 'inherit';
        // 使用箭头函数创建闭包来保存 fooParams 并传递给 foo
        b.addEventListener('click', () => {
            foo(...Object.values(fooParams)); // 将 fooParams 传递给 foo 函数
        });
        if(id){ b.id = id };
        return b;
    }
    //展开指定面板
    function showPanel(panelId){
        let panel = document.getElementById(panelId);
        if (panel.style.right == '-300px') {
            panel.style.right = '0';
        } else {
            panel.style.right = '-300px';
        }
    }
    let btnSwitch = genButton('面板', showPanel, 'btnSwitch', {param1: 'autoSell'});
    let panelFunc = genPanel('autoSell', false);    //初始隐藏
    //加入位置
    let lBtnArea = document.querySelector('.inventory_links');
    lBtnArea.insertBefore(btnSwitch, lBtnArea.children[0]);
    lBtnArea.insertBefore(panelFunc, lBtnArea.children[0]);
    //自动出售(加入到面板中)
    let divName = genDiv();
    let button01 = genButton('自动出售', autoSellFunc, 'autoSell');
    divName.appendChild(button01);
    panelFunc.appendChild(divName);
}
function refreshWindow(id){
    location.reload();
}
function autoSellFunc(){
    // 查询元素,找到当前选择的物品
    const itemInfo0 = document.querySelector('#iteminfo0');
    const itemInfo1 = document.querySelector('#iteminfo1');
    let selectItem;
    // 空值检查
    if (!itemInfo0 || !itemInfo1) {
        console.error('SelectElement not found');
    } else {
        // 根据条件选择元素
        selectItem = itemInfo0.style.position === 'absolute' ? itemInfo1 : itemInfo0;
    }
    selectItem.querySelector('.item_market_action_button_contents').click()
    document.querySelector('#market_sell_dialog_accept_ssa').checked = true

    let commandPrice = selectItem.querySelector(`#${selectItem.id} > :nth-child(3) > div > div > :nth-child(2)`).textContent;
    // 更通用的正则表达式模式
    const regex = /[\d.]+/g; // 使用全局标志 g 来匹配所有出现的数字

    // 使用 match 方法匹配所有出现的数字
    const matches = commandPrice.match(regex);
    let priceFinal;
    if (matches) {
        // 查找符合预期的数字
        const prices = matches.filter(match => /^\d+(\.\d+)?$/.test(match));
        priceFinal = prices.find(p => p.includes('.')); // 假设我们要找的是带有小数点的数字
    } else {
        console.log("未找到匹配的价格");
    }

    // 调用 simulateSequence
    simulateSequence(priceFinal)
        .catch(error => console.error('Error during sequence:', error));
}
//模拟输入，通过冒泡触发输入框中的keyPress和keyUp事件
function simulateInput(text, myInput) {
    var inputElement = document.getElementById(myInput);
    let currentLength = 0;
    for (let i = 0; i < text.length; i++) {
        const char = text[i];
        const keyCode = char.charCodeAt(0);

        // Set the value of the input element
        inputElement.value = text.substring(0, i + 1);

        // Create an input event to update the value visually
        let inputEvent = new Event('input', { bubbles: true });
        inputElement.dispatchEvent(inputEvent);

        // Simulate keypress event
        let keyPressEvent = new KeyboardEvent('keypress', {
            bubbles: true,
            cancelable: true,
            key: char,
            code: `Key${char.toUpperCase()}`, // e.g., 'KeyA' for 'a'
            keyCode: keyCode,
            which: keyCode
        });
        inputElement.dispatchEvent(keyPressEvent);

        // Simulate keyup event
        let keyUpEvent = new KeyboardEvent('keyup', {
            bubbles: true,
            cancelable: true,
            key: char,
            code: `Key${char.toUpperCase()}`, // e.g., 'KeyA' for 'a'
            keyCode: keyCode,
            which: keyCode
        });
        inputElement.dispatchEvent(keyUpEvent);

        // Wait a little bit to mimic typing delay
        if (currentLength < i) {
            setTimeout(() => {}, Math.random() * 50); // Random delay between characters
            currentLength = i;
        }
    }
}

async function simulateSequence(priceFinal) {
    await new Promise(resolve => setTimeout(resolve, 100));
    simulateInput(priceFinal, 'market_sell_buyercurrency_input');
    
    await new Promise(resolve => setTimeout(resolve, 100));
    document.querySelector('#market_sell_dialog_accept').click();

    await new Promise(resolve => setTimeout(resolve, 100));
    document.querySelector('#market_sell_dialog_ok').click();
}